package com.ruoyi.common.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;

import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * mybatis-plus 自动填充字段
 *
 * @author theodo
 */
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_TIME = "createTime";
    private final static String CREATE_BY = "createBy";
    private final static String UPDATE_TIME = "updateTime";
    private final static String UPDATE_BY = "updateBy";
    private final static String DEL_FLAG = "delFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        // 创建时间
        strictInsertFill(metaObject, CREATE_TIME, Date.class, date);
        // 更新时间
        strictInsertFill(metaObject, UPDATE_TIME, Date.class, date);
        // 删除标识
        // strictInsertFill(metaObject, DEL_FLAG, Integer.class, 0);

//        if (StringUtils.isNotNull(SecurityUtils.getAuthentication())) {
//            LoginUser loginUser = SecurityUtils.getLoginUser();
//            // 创建者
//            strictInsertFill(metaObject, CREATE_BY, String.class, loginUser.getUsername());
//            // 更新者
//            strictInsertFill(metaObject, UPDATE_BY, String.class, loginUser.getUsername());
//        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
//        if (StringUtils.isNotNull(SecurityUtils.getAuthentication())) {
//            LoginUser loginUser = SecurityUtils.getLoginUser();
//            // 更新者
//            strictUpdateFill(metaObject, UPDATE_BY, String.class, loginUser.getUsername());
//        }
        // 更新时间
        strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
    }

    /**
     * 严格模式填充策略,默认有值不覆盖,如果提供的值为null也不填充
     * modify-author: fsd
     * modify-issue: 重写strictFillStrategy方法，解决null值不自动填充问题
     *
     * @param metaObject metaObject meta object parameter
     * @param fieldName  java bean property name
     * @param fieldVal   java bean property value of Supplier
     * @return this
     * @since 3.3.0
     */
    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) {
            metaObject.setValue(fieldName, obj);
        }
        return this;
    }
}
